<template>
  <div class="page-container container" v-loading="state.loading">
    <!-- 账单主体信息 -->
    <div class="detailContent">
      <div class="topBox">
        <div class="codebox">{{ state.type == 1?'收款编号：':'付款编号：'}}{{ state.info.doccode }}</div>
        <div v-if="state.info.docstatus == 0" class="status statusType1">
          待提交
        </div>
        <div v-if="state.info.docstatus == 1" class="status statusType2">
          待核销
        </div>
        <div v-if="state.info.docstatus == -1" class="status statusType3">
          未销完
        </div>
        <div v-if="state.info.docstatus == 2" class="status statusType4">
          已核销
        </div>
      </div>
      <div class="messBox">
        <div class="messItem">
          <div class="messLabel">结算单位：</div>
          <div class="messValue">{{ state.info.entFullname }}</div>
        </div>
        <div class="messItem">
          <div class="messLabel">对方账户：</div>
          <div class="messValue">{{ state.info.bankAccount }}</div>
        </div>
      </div>

      <div class="messBox">
        <div class="messItem">
          <div class="messLabel">{{ state.type == 1?'收款币种：':'付款币种：'}}</div>
          <div class="messValue">{{ state.info.currencyCode }}</div>
        </div>
        <div class="messItem">
          <div class="messLabel">{{ state.type == 1?'收款金额：':'付款金额：'}}</div>
          <div class="messValue">{{ state.info.money }}</div>
        </div>
        <div class="messItem">
          <div class="messLabel">已销账金额：</div>
          <div class="messValue">{{ state.info.totalAmount }}</div>
        </div>
      </div>
    </div>
    <!-- 操作按钮栏 -->
    <div class="tab-box in-container" v-if="state.info.docstatus != 2">
      <el-button link @click="save" type="primary"> 待核销信息 </el-button>
      <el-button link @click="refresh" type="primary"> 刷新 </el-button>
    </div>
    <!-- 账单信息 -->
    <div class="detailContent">
      <div class="detailTop">
        <span class="detailTopTitleIcon"></span>
        <span class="detailTopTitle">待核销信息</span>
      </div>
      <div class="billBox">
        <el-form label-width="80" :size="'small'" :inline="true">
          <el-row>
            <el-col :span="6">
              <el-form-item label="核销币种">
                <el-select
                  v-model="state.info.currencyCode"
                  placeholder="请选择币种"
                  style="width: 239px"
                  clearable
                  filterable
                  remote
                  :remote-method="getCurrentData"
                  :loading="state.currentLoading"
                  v-if="state.info.docstatus != 2"
                >
                  <el-option
                    v-for="item in state.current"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span style="float: left"> {{ item.label }}</span>
                  </el-option>
                </el-select>
                <span v-else>{{ state.info.currencyCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="核销汇率">
                <el-input
                  v-model="state.info.rate"
                  placeholder="请输入核销汇率"
                  style="width: 239px"
                  @input="state.info.rate = validateOnlyNumber(state.info.rate)"
                  @change="moneyChange"
                  v-if="state.info.docstatus != 2"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="待销账金额">
                <el-input
                  v-model="state.info.waitmoney"
                  placeholder="请输入待销账金额"
                  style="width: 239px"
                  @input="
                    state.info.money = validateOnlyNumber(state.info.money)
                  "
                  @change="moneyChange"
                  v-if="state.info.docstatus != 2"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <!-- 费用信息 -->
    <div class="detailContent">
      <div class="detailTop">
        <span class="detailTopTitleIcon"></span>
        <span class="detailTopTitle">核销</span>
      </div>
      <div class="tableBox">
        <div class="tableleft">
          <div class="tableContent">
            <div class="searchBox">
              <div class="searchlabel">核销方式：</div>
              <el-select
                size="small"
                style="width: 120px"
                v-model="state.search.type"
                @change="searchChange"
              >
                <el-option label="按账单" :value="1"></el-option>
                <el-option label="按发票" :value="2"></el-option>
                <el-option label="按提单" :value="3"></el-option>
              </el-select>
              <el-input
                class="searchinput"
                v-model="state.search.keyword"
                :placeholder="state.search.placeholder"
              ></el-input>
              <el-button type="primary" size="small"
                ><el-icon><Search /></el-icon
              ></el-button>
            </div>
            <!-- 发票 -->
            <AppPageTable
              stripe
              :data="state.tableData.data"
              @change="getFeeList"
              :height="'400'"
              :option="state.tableData.option"
              @update:option="upDataOption"
              v-loading="state.tableDataLoading"
            >
              <el-table-column
                type="radio"
                width="40"
                align="center"
                fixed="left"
              />

              <el-table-column
                prop="blNo"
                label="发票日期"
                show-overflow-tooltip
                align="center"
                v-if="state.search.type == 1"
              >
              </el-table-column>

              <el-table-column
                prop="blNo"
                label="开航日期"
                show-overflow-tooltip
                align="center"
                v-if="state.search.type == 2"
              >
              </el-table-column>

              <el-table-column
                prop="blNo"
                label="账单日期"
                show-overflow-tooltip
                align="center"
                v-if="state.search.type == 3"
              >
              </el-table-column>

              <el-table-column
                prop="blNo"
                label="发票编号"
                show-overflow-tooltip
                align="center"
                v-if="state.search.type == 1"
              >
              </el-table-column>

              <el-table-column
                prop="blNo"
                label="提单号"
                show-overflow-tooltip
                align="center"
                v-if="state.search.type == 2"
              >
              </el-table-column>

              <el-table-column
                prop="blNo"
                label="账单编号"
                show-overflow-tooltip
                align="center"
                v-if="state.search.type == 3"
              >
              </el-table-column>

              <el-table-column
                prop="blNo"
                label="发票状态"
                show-overflow-tooltip
                align="center"
                v-if="state.search.type == 1"
              >
              </el-table-column>

              <el-table-column
                prop="blNo"
                label="提单状态"
                show-overflow-tooltip
                align="center"
                v-if="state.search.type == 2"
              >
              </el-table-column>

              <el-table-column
                prop="blNo"
                label="账单状态"
                show-overflow-tooltip
                align="center"
                v-if="state.search.type == 3"
              >
              </el-table-column>
            </AppPageTable>
          </div>
        </div>
        <div class="tableborder"></div>
        <div class="tableright">
          <div class="tableContent">
            <div class="searchBox">
              <el-button type="primary" size="small">兑入销账金额</el-button>
              <div class="priceBox">
                <div class="priceIcon"></div>
                <div class="priceItem">
                  发票金额：<span>{{ state.allprice }}</span>
                </div>
                <div class="priceItem">
                  确认兑换金额：<span>{{ state.outprice }}</span>
                </div>
              </div>
            </div>
            <el-table
              stripe
              border
              size="small"
              ref="tableRef"
              height="400"
              :data="state.FeeList"
              :cell-class-name="tableCellClassName"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                align="center"
                width="40"
                type="selection"
                fixed="left"
              />

              <el-table-column
                label="提单号"
                prop="blNo"
                align="center"
                showOverflowTooltip
              ></el-table-column>

              <el-table-column
                label="费用名称"
                prop="feeName"
                align="center"
                showOverflowTooltip
              ></el-table-column>

              <el-table-column
                label="发票币种"
                prop="currency"
                align="center"
                showOverflowTooltip
              ></el-table-column>

              <el-table-column
                label="发票汇率"
                prop="exchangeRate"
                align="center"
                showOverflowTooltip
              ></el-table-column>

              <el-table-column
                label="发票金额"
                prop="totalmoney"
                align="center"
                showOverflowTooltip
              ></el-table-column>

              <el-table-column
                label="确认兑现金额"
                prop="billmoney"
                align="center"
                showOverflowTooltip
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.billmoney"
                    class="alignCenter"
                    @input="
                      scope.row.billmoney = validateOnlyNumber(
                        scope.row.billmoney
                      )
                    "
                    @change="handleRowChange(scope.row)"
                    v-if="state.info.docstatus != 2"
                  ></el-input>
                  <span v-else>{{ scope.row.billmoney }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive, computed, toRaw } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/public/request";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import AppSearchForm from "@/components/AppSearchForm.vue";
import {
  decimal_NUM,
  validateOnlyNumber,
  Number_SubAll,
} from "@/utils/validate.js";
import { RefreshRight, Search } from "@element-plus/icons";

const Route = useRoute();
const Router = useRouter();
const Store = useStore();

const state = reactive({
  loading: false,
  type: 1,
  info: {
    doccode: "112233",
    memo: "",
    entId: "",
    entFullname: "什么什么公司",
    docdate: "",
    docstatus: 0,
    doctype: 1,
    companyId: "",
    currencyCode: "RMB",
    currencyName: "",
    version: "",
    bankAccount: "12345677890",
    bankName: "",
    bankAccountName: "",
    money: "1234",
    totalAmount: "1234",
    createBy: "",
    createTime: "",
    updateBy: "",
    updateTime: "",
    id: 0,
  },
  copyinfo: {
    doccode: "",
    memo: "",
    entId: "",
    entFullname: "",
    docdate: "",
    docstatus: 0,
    doctype: 1,
    companyId: "",
    currencyCode: "",
    currencyName: "",
    version: "",
    bankAccount: "",
    bankName: "",
    bankAccountName: "",
    money: "",
    totalAmount: "",
    createBy: "",
    createTime: "",
    updateBy: "",
    updateTime: "",
    id: 0,
  },
  FeeList: [],
  CopyFeeList: [],
  currentLoading: false,
  current: [],
  allprice: 0,
  outprice: 0,
  show: false,
  tableSelect: [],
  tableDataLoading: false,
  //表格数据
  tableData: {
    data: [],
    option: useTableOption(),
  },
  // 查询条件
  query: {
    // 收支类型 0 付款 1 收款
    isIncome: 0,
    // 结算单位
    entId: "",
    // 币种
    currency: "",

    // 预计开航
    etdDate: [],
    // 实际开航
    atdDate: [],
    // 提单号
    blNo: "",

    // 审核状态 0未审 1已审
    feeStatus: 0,
  },
  search: {
    feename: "",
    type: 1,
    keyword: "",
    placeholder: "请输入账单编号",
  },
});

// 预计开航
const etdTime = computed({
  get: function () {
    return [state.query.etdDate[0], state.query.etdDate[1]];
  },
  set: function (val) {
    if (val) {
      state.query.etdDate[0] = val[0];
      state.query.etdDate[1] = val[1];
    } else {
      state.query.etdDate[0] = "";
      state.query.etdDate[1] = "";
    }
  },
});

// 实际开航
const atdTime = computed({
  get: function () {
    return [state.query.atdDate[0], state.query.atdDate[1]];
  },
  set: function (val) {
    if (val) {
      state.query.atdDate[0] = val[0];
      state.query.atdDate[1] = val[1];
    } else {
      state.query.atdDate[0] = "";
      state.query.atdDate[1] = "";
    }
  },
});

const searchChange = (val) => {
  if (val == 1) {
    state.search.keyword = "";
    state.search.placeholder = "请输入发票编号";
  }
  if (val == 2) {
    state.search.keyword = "";
    state.search.placeholder = "请输入发票编号";
  }
  if (val == 3) {
    state.search.keyword = "";
    state.search.placeholder = "请输入提单号";
  }
};

// 打开添加明细弹窗
const openAdd = async () => {
  // if (!state.info.currencyCode) {
  //   ElMessage.warning("请选择帐单币种");
  //   return;
  // }
  // await getFeeList();
  state.show = true;
};

const getFeeList = async () => {
  state.tableDataLoading = true;
  let res = await request.post("/api/docworkfee/getWorkFeeBalance", {
    PageIndex: state.tableData.option.page,
    PageSize: state.tableData.option.pageSize,
    ...state.query,
  });
  state.tableData.data = res.content;
  state.tableData.option.total = res.totalElements;
  state.tableDataLoading = false;
};
const FeeReset = () => {
  state.query.blNo = "";
  state.query.atdDate = [];
  state.query.etdDate = [];
};

const tableCellClassName = ({ row, column, rowIndex, columnIndex }) => {
  column.index = columnIndex;
  row.index = rowIndex;
};

/**
 * 选择后的数据
 */
const handleSelectionChange = (val) => {
  let arr = [];
  for (let item of val) {
    let ret = toRaw(item);
    if (ret !== undefined) {
      arr.push(ret);
    }
  }
  state.tableSelect = arr;
};

// 获取币种类型
const getCurrentData = async (val) => {
  state.currentLoading = true;
  let res = await request.get("/api/base/currency/dropdownlist", {
    keywords: val,
  });
  state.current = res.map((item) => {
    return {
      label: item.currencyCode + "|" + item.currencyName,
      value: item.currencyCode,
    };
  });
  state.currentLoading = false;
};

// 获取账单详情
const getInfo = async () => {
  let res = await request.get("/api/docbalance/GetBalanceInfo", {
    id: state.info.id,
  });
  for (let key in state.info) {
    state.info[key] = res.data.docBalancehd[key];
    state.copyinfo[key] = res.data.docBalancehd[key];
  }
  var price = 0;
  res.data.feeList.forEach((item) => {
    item.billmoney = item.totalmoney;
    price = decimal_NUM([price, item.totalmoney]);
  });
  state.FeeList = res.data.feeList;
  state.CopyFeeList = res.data.feeList;

  state.copyinfo.money = price;

  state.query.isIncome = state.info.doctype;
  state.query.entId = state.info.entId;
  state.query.currency = state.info.currencyCode;
  setAllPrice();
};

// 计算总金额
const setAllPrice = () => {
  var totalNum = 0,
    billNum = 0;
  state.FeeList.forEach((item) => {
    totalNum = decimal_NUM([totalNum, item.totalmoney]);
    billNum = decimal_NUM([billNum, item.billmoney]);
  });
  state.allprice = totalNum;
  state.outprice = billNum;

  state.info.money = billNum;
};

const handleRowChange = (row) => {
  if (row.billmoney > row.totalmoney) {
    row.billmoney = row.totalmoney;
  }
  if (!row.billmoney) {
    row.billmoney = 0;
  }
  setAllPrice();
};

const moneyChange = () => {
  if (state.info.money > state.allprice) {
    state.info.money = state.allprice;
  }
};

// 选中的表格数据
const selectOver = () => {
  let CpoySelectTableData = JSON.parse(
    JSON.stringify(state.tableData.option.selected)
  );
  let newArray = [];

  CpoySelectTableData.forEach((t) => {
    if (!state.FeeList.find((item) => t.id == item.id)) {
      newArray.push(t);
    }
  });
  newArray.forEach((item) => {
    item.billmoney = item.totalmoney;
  });

  state.FeeList = [...state.FeeList, ...newArray];
  state.show = false;
  setAllPrice();
};

// 删除明细
const delFee = () => {
  if (state.tableSelect.length == 0) {
    ElMessage.warning("请选择需要删除的费用明细");
    return;
  }
  ElMessageBox.confirm("是否确定执行删除操作？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let newArray = [];

    state.FeeList.forEach((t) => {
      if (!state.tableSelect.find((item) => t == item)) {
        newArray.push(t);
      }
    });

    state.FeeList = newArray;
    setAllPrice();
  });
};
// 费用列表刷新
const feerefrsh = () => {
  let feestatus = FeeEdit();
  if (feestatus) {
    ElMessageBox.confirm("当前数据未保存，是否刷新？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      state.FeeList = state.CopyFeeList;
      ElMessage.success("成功");
    });
  } else {
    ElMessage.success("成功");
  }
};
// 同步进费用
const SynchronousFee = () => {
  if (!state.info.money) {
    ElMessage.warning("请输入账单金额");
    return;
  }
  ElMessageBox.confirm("是否确定执行同步操作？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    var SynchronousNum = state.info.money;
    state.FeeList.forEach((item) => {
      item.billmoney =
        item.totalmoney < SynchronousNum ? item.totalmoney : SynchronousNum;
      SynchronousNum =
        Number_SubAll(SynchronousNum, item.totalmoney) > 0
          ? Number_SubAll(SynchronousNum, item.totalmoney)
          : 0;
    });
    setAllPrice();
  });
};

// 保存账单信息
const save = async () => {
  
  Router.push({
    path: "/finance/writeOffRegistration",
    query: {
      id: 0,
      title: `登记详情${'112233'}`,
      iscopy: false,
    },
  });

  Router.closeTab();
};
// 刷新
const refresh = async () => {
  let res = isEdit();

  if (res) {
    ElMessageBox.confirm("当前数据未保存，是否刷新？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      // getInfo();
      ElMessage.success("成功");
    });
  } else {
    ElMessage.success("成功");
  }
};
const isEdit = () => {
  if (state.info.currencyCode !== state.copyinfo.currencyCode) {
    return true;
  }

  if (Number(state.info.money) !== Number(state.copyinfo.money)) {
    return true;
  }

  if (state.info.memo !== state.copyinfo.memo) {
    return true;
  }

  let feestatus = FeeEdit();

  if (feestatus) {
    return true;
  }

  return false;
};
const FeeEdit = () => {
  var feeboolean = false;
  if (state.FeeList.length !== state.CopyFeeList.length) {
    feeboolean = true;
  }

  state.FeeList.forEach((item, index) => {
    if (Number(item.billmoney) !== Number(state.CopyFeeList[index].billmoney)) {
      feeboolean = true;
    }
  });

  return feeboolean;
};

onMounted(() => {
  if (Route.query != {}) {
    state.info.id = Route.query.id;
    state.type = Route.query.type;
    Store.dispatch("tab/modifyTabTitle", {
      path: Route.fullPath,
      title: Route.query.title,
    });
  }
  // getInfo();
});
</script>
<style lang="scss" scoped>
.tab-box {
  height: 38px;
  display: flex;
  align-items: center;
  padding: 0px 16px;
  border: none;
  border-radius: 2px;
  margin-bottom: 12px;

  :deep(.el-button) {
    font-size: 14px;
    margin: 0 10px;
  }
}
.container {
  display: flex;
  flex-direction: column;

  .content {
    flex: 1;
    height: auto;
    padding: 0 0 8px 0;
  }

  :deep(.el-radio-group) {
    height: 28px;
  }

  :deep(.el-radio) {
    margin-right: 15px;

    .el-radio__inner {
      width: 12px;
      height: 12px;
    }

    .el-radio__label {
      font-size: 12px;
    }
  }

  :deep(.el-form-item) {
    width: 100%;
  }

  :deep(.el-select) {
    // width: 100%;
  }

  :deep(.el-date-editor) {
    width: 100%;
  }

  :deep(.el-tabs) {
    height: 100%;

    .el-tabs__header {
      padding: 0 16px;
    }

    .el-tabs__content {
      height: calc(100% - 55px);

      .el-tab-pane {
        height: 100%;
      }
    }
  }

  .form {
    height: 100%;
  }
}
.detailContent {
  background: #ffffff;
  box-sizing: border-box;
  padding: 8px 12px;
  margin-bottom: 12px;
  .topBox {
    display: flex;
    align-items: center;
    .codebox {
      color: #000000d8;
      font-size: 14px;
      line-height: 22px;
      letter-spacing: 0px;
      text-align: left;
      margin-right: 8px;
      font-weight: 600;
    }
    .status {
      border: 1px solid transparent;
      box-sizing: border-box;
      padding: 0 4px;
      font-size: 12px;
      line-height: 22px;
      letter-spacing: 0px;
      border-radius: 2px;
      margin-left: 8px;
    }
    .statusType1 {
      border-color: #d9d9d9;
      background: #d9d9d919;
      color: #00000099;
    }
    .statusType2 {
      border-color: #fa8c16;
      background: #fff7e6;
      color: #fa8c16;
    }
    .statusType3 {
      border-color: #f5222d;
      background: #fff1f0;
      color: #f5222d;
    }
    .statusType4 {
      border-color: #2cbe60;
      background: #eefbf3;
      color: #2cbe60;
    }
  }
}
.messBox {
  margin-top: 12px;
  display: flex;
  .messItem {
    width: 240px;
    display: flex;
    .messLabel {
      color: #00000099;
      font-size: 12px;
      line-height: 20px;
      letter-spacing: 0px;
      margin-right: 4px;
    }
    .messValue {
      flex: 1;
      color: #00000099;
      font-size: 12px;
      line-height: 20px;
      letter-spacing: 0px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.detailTop {
  display: flex;
  align-items: center;
  .detailTopTitle {
    color: #000000d8;
    font-weight: 600;
    font-size: 14px;
    line-height: 22px;
    letter-spacing: 0px;
    position: relative;
  }
  .detailTopTitleIcon {
    display: inline-block;
    height: 22px;
    width: 2px;
    background: #5a9cf8;
    margin-right: 8px;
  }
}
.billBox {
  margin-top: 8px;
}
.btnBox {
  margin-top: 8px;
  display: flex;
}
.priceBox {
  display: flex;
  align-items: center;
  flex: 1;
  .priceIcon {
    background: #5a9cf8;
    width: 2px;
    height: 20px;
    margin-left: 12px;
    margin-right: 8px;
  }
  .priceItem {
    color: #000000d8;
    font-size: 12px;
    line-height: 20px;
    letter-spacing: 0px;
    margin-right: 24px;
  }
}
.tableBox {
  margin-top: 12px;
  display: flex;

  :deep(.el-table) {
    .el-table__header th {
      background-color: #f7f8fa;
    }

    .cell {
      height: 28px;
      line-height: 28px;
    }

    .el-checkbox {
      height: 28px;
    }
  }
  :deep(.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner) {
    background-color: #409eff;
  }
  :deep(.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after) {
    border-color: #ffffff;
  }

  .tableleft {
    width: 424px;
  }
  .tableborder {
    width: 1px;
    background: #d9d9d9;
    margin: 0 12px;
    height: 456px;
  }
  .tableright {
    flex: 1;
  }

  .tableContent {
    width: 100%;
    height: 480px;
  }
}

:deep(.finacial-dailog) {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }

  .el-dialog {
    min-width: 630px;
  }

  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
  }

  .el-dialog__body {
    padding-left: 0;
    padding-right: 0;
  }
}
.button-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.from-container {
  border: 1px solid #e8e8e8;
  padding: 6px;
  margin-bottom: 8px;
}

.alignCenter {
  :deep(.el-input__inner) {
    text-align: center;
  }
}

.table-container {
  border-radius: 2px;
  border: 1px solid #e7e7e7;
  height: 500px;
  width: 100%;
  box-sizing: border-box;
  padding: 12px;
}
.searchBox {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.feeInput {
  width: 240px;
  margin-right: 8px;
}
.searchinput {
  flex: 1;
  margin: 0 4px;
}
</style>
